import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/open_page_util.dart';

class ActivityWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => ActivityWidgetState();
}

class ActivityWidgetState extends State<ActivityWidget> {
  final flutterWebviewPlugin = new FlutterWebviewPlugin();
  String url = 'https://www.vip.com';

  double _bottomPadding = 0.0;

  StreamSubscription<String> _onWebviewMessaged;

  @override
  void initState() {
    super.initState();
    _onWebviewMessaged =
        flutterWebviewPlugin.onWebviewMessage.listen((String message) {
      if (message != null && message.isNotEmpty) {
        Map<String, dynamic> params = json.decode(message);
        if (params != null) {
          OpenPageUtil.openPage(
              context, params["type"], params["pageUrl"], params["params"],
              name: params["name"],
              shareTitle: params["shareTitle"],
              shareAvatar: params["shareAvatar"],
              shareContent: params["shareContent"],
              showTips: params["showTips"]);
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _onWebviewMessaged.cancel();
    flutterWebviewPlugin.close();
  }

  @override
  Widget build(BuildContext context) {
    _getInfo();
    flutterWebviewPlugin.close();
    flutterWebviewPlugin.launch(url,
        rect: new Rect.fromLTWH(0.0, 0.0, MediaQuery.of(context).size.width,
            MediaQuery.of(context).size.height - 56.0 - _bottomPadding),
        userAgent: Api.kWebViewUserAgent,
        enableMessaging: true);
    return Container();
  }

  _getInfo() {
    if (_isIPhoneX(MediaQuery.of(context))) {
      if (!mounted) return;
      setState(() {
        _bottomPadding = 34.0 - 8.0;
      });
    }
  }

  bool _isIPhoneX(MediaQueryData mediaQuery) {
    if (Platform.isIOS) {
      var size = mediaQuery.size;
      if (size.height == 812.0 || size.width == 812.0) {
        return true;
      }
    }
    return false;
  }
}
